package com.ww.springboot.boot.thread.study.base.exception;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 描述：线程池-异常:其中一个线程异常时 关闭线程池 并将异常返回
 *
 * @author wanwei
 * @since 2021-10-20 11:25
 */
public class ExceptionHandle {

    public static void main(String[] args) {

        AtomicReference<String> error = getStringAtomicReference();
        System.out.println("异常:"+error);
    }

    private static AtomicReference<String> getStringAtomicReference() {
        AtomicReference<String> error = new AtomicReference<>("");

        ExecutorService executorService = Executors.newFixedThreadPool(10);

        try {
            for (int i = 0; i < 10; i++) {
                int finalI = i;
                Thread thread = new Thread(() -> {
                    if (finalI % 3 == 0) {
                        throw new RuntimeException("xxxxxxxxxxxxx");
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {

                    }
                });
                //设置该对象的默认异常处理器
                thread.setDefaultUncaughtExceptionHandler((Thread t, Throwable e) -> {
                    error.set(e.getMessage());
                    //立即关闭线程池
                    executorService.shutdownNow();
                });
                //没有关闭才往线程池中发布任务
                if(!executorService.isShutdown()){
                    executorService.execute(thread);
                }
            }
            executorService.shutdown();
        } catch (Exception e) {
            System.out.println("------捕获异常-----");
            e.printStackTrace();
        }
        return error;
    }
}
